/*
 * This file is part of PDBEdit.
 * 
 * PDBEdit is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * PDBEdit is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with PDBEdit.  If not, see <http://www.gnu.org/licenses/>.
 *  
 * Creation date : 15/09/2010
 * Copyright (c) Guerfyld 2010. All rights reserved.
 * http://......
 */
package filechooser;

import java.util.*;
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.io.file.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.RecordStore;

/**
 * The FileChooser class browse and select a file
 *
 * @author guerfyld
 * @version 1.0
 */
public class FileChooser implements CommandListener {
	// Constants
	public static final Command OPEN = new Command("Open", Command.ITEM, 1);
	public static final Command EXIT = new Command("Exit", Command.EXIT, 3);
	private static final String ROOT = "/";
	private static final String UPDIRECTORY = "..";
	private static final String RSNAME = "OPENDIR";
	// 
	private MIDlet myMidlet;
	private String filter;
	private String curDirName;
	private String fileUrl;
	private Image dirIcon, fileIcon;
	private List fileList;
	private CommandListener listener;

	/**
	 * Constructor
	 */
	public FileChooser(MIDlet midlet, String flt) {
		// Init
		myMidlet = midlet;
		filter   = flt;
		// Load start directory
		try {
			RecordStore rs = RecordStore.openRecordStore(RSNAME, true);
			curDirName = new String(rs.getRecord(1));
			rs.closeRecordStore();
		}
		catch(Exception e) {
			curDirName = ROOT;
		}
		// Load icons list
		try {
			dirIcon = Image.createImage("/icons/dir.png");
		}
		catch(Exception e) {
			dirIcon = null;
		}
		try {
			fileIcon = Image.createImage("/icons/file.png");
		}
		catch(Exception e) {
			fileIcon = null;
		}
	}

	/**
	 * Show directory file list
	 */
	public void showDir() {
		FileConnection curDir = null;
		Enumeration ldir;

		fileList = new List(curDirName, List.IMPLICIT);
		try {
			// Read file directory
			if (ROOT.equals(curDirName)) {
				ldir = FileSystemRegistry.listRoots();
			}
			else {
				curDir = (FileConnection)Connector.open("file://" + curDirName);
				ldir = curDir.list();
				fileList.append(UPDIRECTORY, dirIcon);
			}
			while (ldir.hasMoreElements()) {
				String fileName = (String)ldir.nextElement();
				if (fileName.charAt(fileName.length()-1) == '/')
					fileList.append(fileName, dirIcon);
				else if (fileName.toUpperCase().endsWith(filter))
					fileList.append(fileName, fileIcon);
            		}

			fileList.setSelectCommand(OPEN);
			fileList.addCommand(EXIT);
			fileList.setCommandListener(this);

			if (curDir != null) curDir.close();
			Display.getDisplay(myMidlet).setCurrent(fileList);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Implementation of CommandListener :
	 * Respond to a button push.
	 */
	public void commandAction(Command command, Displayable d) {
		if (command == OPEN) {
			String fileName = fileList.getString(fileList.getSelectedIndex());
			if (UPDIRECTORY.equals(fileName)) {
				// Go up one directory
				int i = curDirName.lastIndexOf('/', curDirName.length()-2);
				if (i != -1)
					curDirName = curDirName.substring(0, i+1);
				else
					curDirName = ROOT;
				showCurDir();
			}
			else if (fileName.charAt(fileName.length()-1) == '/') {
				// Go to directory
				curDirName += fileName;
				showCurDir();
			}
			else {
				// Save current directory
				try {
					RecordStore rs = RecordStore.openRecordStore(RSNAME, true);
					if (rs.getNumRecords() == 0)
						rs.addRecord(curDirName.getBytes(), 0, curDirName.length());
					else
						rs.setRecord(1, curDirName.getBytes(), 0, curDirName.length());
					rs.closeRecordStore();
				}
				catch (Exception e) {
					e.printStackTrace();
				}
				// Open file
				fileUrl = "file://"+curDirName+fileName;
				listener.commandAction(command, d);
			}
		}
		else if (command == EXIT) {
			// Exit
			listener.commandAction(command, d);
		}
	}

	/*
	 * Set command listener
	 */
	public void setCommandListener(CommandListener l) {
		listener = l;
	}

	/**
	 * Get file url to open
	 */
	public String getFileUrl() {
		return fileUrl;
	}

	/**
	 * Get file current directory
	 */
	public String getCurDir() {
		return curDirName;
	}

	// Update directory structure in another thread
	private void showCurDir() {
		new Thread(new Runnable() {
			public void run() {
				showDir();
			}
		}).start();
	}
}
